Exercise 4

## Data overview
library(MASS)
data("Boston")
str(Boston)
## 'data.frame':    506 obs. of  14 variables:
##  $ crim   : num  0.00632 0.02731 0.02729 0.03237 0.06905 ...
##  $ zn     : num  18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
##  $ indus  : num  2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
##  $ chas   : int  0 0 0 0 0 0 0 0 0 0 ...
##  $ nox    : num  0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
##  $ rm     : num  6.58 6.42 7.18 7 7.15 ...
##  $ age    : num  65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
##  $ dis    : num  4.09 4.97 4.97 6.06 6.06 ...
##  $ rad    : int  1 2 2 3 3 3 5 5 5 5 ...
##  $ tax    : num  296 242 242 222 222 222 311 311 311 311 ...
##  $ ptratio: num  15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
##  $ black  : num  397 397 393 395 397 ...
##  $ lstat  : num  4.98 9.14 4.03 2.94 5.33 ...
##  $ medv   : num  24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...
summary(Boston)
##       crim                zn             indus            chas        
##  Min.   : 0.00632   Min.   :  0.00   Min.   : 0.46   Min.   :0.00000  
##  1st Qu.: 0.08204   1st Qu.:  0.00   1st Qu.: 5.19   1st Qu.:0.00000  
##  Median : 0.25651   Median :  0.00   Median : 9.69   Median :0.00000  
##  Mean   : 3.61352   Mean   : 11.36   Mean   :11.14   Mean   :0.06917  
##  3rd Qu.: 3.67708   3rd Qu.: 12.50   3rd Qu.:18.10   3rd Qu.:0.00000  
##  Max.   :88.97620   Max.   :100.00   Max.   :27.74   Max.   :1.00000  
##       nox               rm             age              dis        
##  Min.   :0.3850   Min.   :3.561   Min.   :  2.90   Min.   : 1.130  
##  1st Qu.:0.4490   1st Qu.:5.886   1st Qu.: 45.02   1st Qu.: 2.100  
##  Median :0.5380   Median :6.208   Median : 77.50   Median : 3.207  
##  Mean   :0.5547   Mean   :6.285   Mean   : 68.57   Mean   : 3.795  
##  3rd Qu.:0.6240   3rd Qu.:6.623   3rd Qu.: 94.08   3rd Qu.: 5.188  
##  Max.   :0.8710   Max.   :8.780   Max.   :100.00   Max.   :12.127  
##       rad              tax           ptratio          black       
##  Min.   : 1.000   Min.   :187.0   Min.   :12.60   Min.   :  0.32  
##  1st Qu.: 4.000   1st Qu.:279.0   1st Qu.:17.40   1st Qu.:375.38  
##  Median : 5.000   Median :330.0   Median :19.05   Median :391.44  
##  Mean   : 9.549   Mean   :408.2   Mean   :18.46   Mean   :356.67  
##  3rd Qu.:24.000   3rd Qu.:666.0   3rd Qu.:20.20   3rd Qu.:396.23  
##  Max.   :24.000   Max.   :711.0   Max.   :22.00   Max.   :396.90  
##      lstat            medv      
##  Min.   : 1.73   Min.   : 5.00  
##  1st Qu.: 6.95   1st Qu.:17.02  
##  Median :11.36   Median :21.20  
##  Mean   :12.65   Mean   :22.53  
##  3rd Qu.:16.95   3rd Qu.:25.00  
##  Max.   :37.97   Max.   :50.00
#variables distribution
p <- pairs(Boston)
p
## NULL
#calculate the correlation matrix and round it
cor_matrix<-cor(Boston) 
#print the correlation matrix
cor_matrix
##                crim          zn       indus         chas         nox
## crim     1.00000000 -0.20046922  0.40658341 -0.055891582  0.42097171
## zn      -0.20046922  1.00000000 -0.53382819 -0.042696719 -0.51660371
## indus    0.40658341 -0.53382819  1.00000000  0.062938027  0.76365145
## chas    -0.05589158 -0.04269672  0.06293803  1.000000000  0.09120281
## nox      0.42097171 -0.51660371  0.76365145  0.091202807  1.00000000
## rm      -0.21924670  0.31199059 -0.39167585  0.091251225 -0.30218819
## age      0.35273425 -0.56953734  0.64477851  0.086517774  0.73147010
## dis     -0.37967009  0.66440822 -0.70802699 -0.099175780 -0.76923011
## rad      0.62550515 -0.31194783  0.59512927 -0.007368241  0.61144056
## tax      0.58276431 -0.31456332  0.72076018 -0.035586518  0.66802320
## ptratio  0.28994558 -0.39167855  0.38324756 -0.121515174  0.18893268
## black   -0.38506394  0.17552032 -0.35697654  0.048788485 -0.38005064
## lstat    0.45562148 -0.41299457  0.60379972 -0.053929298  0.59087892
## medv    -0.38830461  0.36044534 -0.48372516  0.175260177 -0.42732077
##                  rm         age         dis          rad         tax
## crim    -0.21924670  0.35273425 -0.37967009  0.625505145  0.58276431
## zn       0.31199059 -0.56953734  0.66440822 -0.311947826 -0.31456332
## indus   -0.39167585  0.64477851 -0.70802699  0.595129275  0.72076018
## chas     0.09125123  0.08651777 -0.09917578 -0.007368241 -0.03558652
## nox     -0.30218819  0.73147010 -0.76923011  0.611440563  0.66802320
## rm       1.00000000 -0.24026493  0.20524621 -0.209846668 -0.29204783
## age     -0.24026493  1.00000000 -0.74788054  0.456022452  0.50645559
## dis      0.20524621 -0.74788054  1.00000000 -0.494587930 -0.53443158
## rad     -0.20984667  0.45602245 -0.49458793  1.000000000  0.91022819
## tax     -0.29204783  0.50645559 -0.53443158  0.910228189  1.00000000
## ptratio -0.35550149  0.26151501 -0.23247054  0.464741179  0.46085304
## black    0.12806864 -0.27353398  0.29151167 -0.444412816 -0.44180801
## lstat   -0.61380827  0.60233853 -0.49699583  0.488676335  0.54399341
## medv     0.69535995 -0.37695457  0.24992873 -0.381626231 -0.46853593
##            ptratio       black      lstat       medv
## crim     0.2899456 -0.38506394  0.4556215 -0.3883046
## zn      -0.3916785  0.17552032 -0.4129946  0.3604453
## indus    0.3832476 -0.35697654  0.6037997 -0.4837252
## chas    -0.1215152  0.04878848 -0.0539293  0.1752602
## nox      0.1889327 -0.38005064  0.5908789 -0.4273208
## rm      -0.3555015  0.12806864 -0.6138083  0.6953599
## age      0.2615150 -0.27353398  0.6023385 -0.3769546
## dis     -0.2324705  0.29151167 -0.4969958  0.2499287
## rad      0.4647412 -0.44441282  0.4886763 -0.3816262
## tax      0.4608530 -0.44180801  0.5439934 -0.4685359
## ptratio  1.0000000 -0.17738330  0.3740443 -0.5077867
## black   -0.1773833  1.00000000 -0.3660869  0.3334608
## lstat    0.3740443 -0.36608690  1.0000000 -0.7376627
## medv    -0.5077867  0.33346082 -0.7376627  1.0000000
#visualize the correlation matrix
library(corrplot)
## corrplot 0.84 loaded
library(tidyverse)
## ── Attaching packages ───────────────────────────────── tidyverse 1.2.1 ──
## ✔ ggplot2 3.2.1     ✔ purrr   0.3.3
## ✔ tibble  2.1.3     ✔ dplyr   0.8.3
## ✔ tidyr   1.0.0     ✔ stringr 1.4.0
## ✔ readr   1.3.1     ✔ forcats 0.4.0
## ── Conflicts ──────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ✖ dplyr::select() masks MASS::select()

corrplot(cor_matrix, method="circle")

corrplot(cor_matrix, method="circle", type = "upper",cl.pos = "b", tl.pos = "d",tl.cex = 0.6)%>%round()

##         crim zn indus chas nox rm age dis rad tax ptratio black lstat medv
## crim       1  0     0    0   0  0   0   0   1   1       0     0     0    0
## zn         0  1    -1    0  -1  0  -1   1   0   0       0     0     0    0
## indus      0 -1     1    0   1  0   1  -1   1   1       0     0     1    0
## chas       0  0     0    1   0  0   0   0   0   0       0     0     0    0
## nox        0 -1     1    0   1  0   1  -1   1   1       0     0     1    0
## rm         0  0     0    0   0  1   0   0   0   0       0     0    -1    1
## age        0 -1     1    0   1  0   1  -1   0   1       0     0     1    0
## dis        0  1    -1    0  -1  0  -1   1   0  -1       0     0     0    0
## rad        1  0     1    0   1  0   0   0   1   1       0     0     0    0
## tax        1  0     1    0   1  0   1  -1   1   1       0     0     1    0
## ptratio    0  0     0    0   0  0   0   0   0   0       1     0     0   -1
## black      0  0     0    0   0  0   0   0   0   0       0     1     0    0
## lstat      0  0     1    0   1 -1   1   0   0   1       0     0     1   -1
## medv       0  0     0    0   0  1   0   0   0   0      -1     0    -1    1

This data has 506 obs. of 14 variables which contain information about different indicators of Boston city as per capita crime rate, index of accessibility to radial highways and etc. In the first plot we see the distibution of variables. It looks like only rm has a normal distribution while crime, chas, lstat are shifted to the left, age to the right and etc. In the second plot positive correlations are displayed in blue and negative correlations in red color. Color intensity and the size of the circle are proportional to the correlation coefficients. For example, the is strong positive correlation between such variables as crime and rad and tax, between indus and nox, age and tax. Negative correlations between dis and nox,age and dis, medv and lstat.

## Scaling and factor variable

#center and standardize variables
boston_scaled <- scale (Boston)
#summaries of the scaled variables
summary(boston_scaled) 
##       crim                 zn               indus        
##  Min.   :-0.419367   Min.   :-0.48724   Min.   :-1.5563  
##  1st Qu.:-0.410563   1st Qu.:-0.48724   1st Qu.:-0.8668  
##  Median :-0.390280   Median :-0.48724   Median :-0.2109  
##  Mean   : 0.000000   Mean   : 0.00000   Mean   : 0.0000  
##  3rd Qu.: 0.007389   3rd Qu.: 0.04872   3rd Qu.: 1.0150  
##  Max.   : 9.924110   Max.   : 3.80047   Max.   : 2.4202  
##       chas              nox                rm               age         
##  Min.   :-0.2723   Min.   :-1.4644   Min.   :-3.8764   Min.   :-2.3331  
##  1st Qu.:-0.2723   1st Qu.:-0.9121   1st Qu.:-0.5681   1st Qu.:-0.8366  
##  Median :-0.2723   Median :-0.1441   Median :-0.1084   Median : 0.3171  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.:-0.2723   3rd Qu.: 0.5981   3rd Qu.: 0.4823   3rd Qu.: 0.9059  
##  Max.   : 3.6648   Max.   : 2.7296   Max.   : 3.5515   Max.   : 1.1164  
##       dis               rad               tax             ptratio       
##  Min.   :-1.2658   Min.   :-0.9819   Min.   :-1.3127   Min.   :-2.7047  
##  1st Qu.:-0.8049   1st Qu.:-0.6373   1st Qu.:-0.7668   1st Qu.:-0.4876  
##  Median :-0.2790   Median :-0.5225   Median :-0.4642   Median : 0.2746  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.6617   3rd Qu.: 1.6596   3rd Qu.: 1.5294   3rd Qu.: 0.8058  
##  Max.   : 3.9566   Max.   : 1.6596   Max.   : 1.7964   Max.   : 1.6372  
##      black             lstat              medv        
##  Min.   :-3.9033   Min.   :-1.5296   Min.   :-1.9063  
##  1st Qu.: 0.2049   1st Qu.:-0.7986   1st Qu.:-0.5989  
##  Median : 0.3808   Median :-0.1811   Median :-0.1449  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.4332   3rd Qu.: 0.6024   3rd Qu.: 0.2683  
##  Max.   : 0.4406   Max.   : 3.5453   Max.   : 2.9865
#class of the boston_scaled object
class(boston_scaled)
## [1] "matrix"
#change the object to data frame
boston_scaled <- as.data.frame(boston_scaled)
#create a quantile vector of crim and print it
bins <- quantile(boston_scaled$crim)
bins
##           0%          25%          50%          75%         100% 
## -0.419366929 -0.410563278 -0.390280295  0.007389247  9.924109610
#create a categorical variable 'crime'
vector <- c("low","med_low","med_high","high")
crime <- cut(boston_scaled$crim, breaks = bins, include.lowest = TRUE, label=vector)
#look at the table of the new factor crime
table(crime)
## crime
##      low  med_low med_high     high 
##      127      126      126      127
# remove original crim from the dataset
boston_scaled <- dplyr::select(boston_scaled, -crim)
#add the new categorical value to scaled data
boston_scaled <- data.frame(boston_scaled, crime)

## Train and test sets
#number of rows in the Boston dataset 
n <- nrow(boston_scaled)
#choose randomly 80% of the rows
ind <- sample(n,  size = n * 0.8)
#create train set
train <- boston_scaled[ind,]
#create test set 
test <- boston_scaled[-ind,]
#save the correct classes from test data
correct_classes <- c(test$crime)
#remove the crime variable from test data
test <- dplyr::select(test, -crime)

str(train)
## 'data.frame':    404 obs. of  14 variables:
##  $ zn     : num  -0.487 -0.487 -0.487 -0.487 -0.487 ...
##  $ indus  : num  -1.2648 1.015 -0.4368 -0.0797 -0.0797 ...
##  $ chas   : num  -0.272 3.665 -0.272 3.665 -0.272 ...
##  $ nox    : num  -0.576 1.858 -0.144 -0.567 -0.567 ...
##  $ rm     : num  1.239 0.157 -0.303 -1.339 -1.242 ...
##  $ age    : num  0.839 0.797 1.116 1.116 -2.088 ...
##  $ dis    : num  -0.5197 -0.6125 0.1804 0.038 -0.0986 ...
##  $ rad    : num  -0.752 1.66 -0.637 -0.637 -0.637 ...
##  $ tax    : num  -1.277 1.529 -0.601 -0.779 -0.779 ...
##  $ ptratio: num  -0.3028 0.8058 1.1753 0.0667 0.0667 ...
##  $ black  : num  0.4102 0.3797 0.2197 0.4406 -0.0848 ...
##  $ lstat  : num  -1.0969 0.0864 0.0542 1.4615 2.3662 ...
##  $ medv   : num  1.6709 -0.0906 -0.8734 -0.2754 0.1269 ...
##  $ crime  : Factor w/ 4 levels "low","med_low",..: 2 4 3 3 3 4 3 2 1 1 ...
str(test)
## 'data.frame':    102 obs. of  13 variables:
##  $ zn     : num  0.2845 -0.4872 0.0487 -0.4872 -0.4872 ...
##  $ indus  : num  -1.287 -1.306 -0.476 -0.437 -0.437 ...
##  $ chas   : num  -0.272 -0.272 -0.272 -0.272 -0.272 ...
##  $ nox    : num  -0.144 -0.834 -0.265 -0.144 -0.144 ...
##  $ rm     : num  0.413 1.015 -0.388 -0.641 -0.498 ...
##  $ age    : num  -0.1199 -0.8091 -0.0702 -0.429 -1.3953 ...
##  $ dis    : num  0.14 1.077 0.838 0.334 0.334 ...
##  $ rad    : num  -0.982 -0.752 -0.522 -0.637 -0.637 ...
##  $ tax    : num  -0.666 -1.105 -0.577 -0.601 -0.601 ...
##  $ ptratio: num  -1.458 0.113 -1.504 1.175 1.175 ...
##  $ black  : num  0.441 0.416 0.426 0.427 0.331 ...
##  $ lstat  : num  -1.0745 -1.3602 -0.0312 -0.5858 -0.8504 ...
##  $ medv   : num  0.1595 1.1816 0.0399 -0.2863 0.0617 ...

Here we scale the data which is an operation when we subtract the column means from the corresponding columns and divide the difference with standard deviation. It helps us to have normal distribution of variables later used in clastering. When we create a factor variable’crim’ and use the quantiles as the break points to the variable.Later we divide the dataset to train and test sets, so that 80% of the data belongs to the train set.

# Linear discriminant analysis
lda.fit <- lda(crime ~ ., data = train)
#print the lda.fit object
lda.fit
## Call:
## lda(crime ~ ., data = train)
## 
## Prior probabilities of groups:
##       low   med_low  med_high      high 
## 0.2475248 0.2450495 0.2549505 0.2524752 
## 
## Group means:
##                   zn      indus         chas        nox         rm
## low       0.95964878 -0.8673138 -0.154216061 -0.8872033  0.3852534
## med_low  -0.06843018 -0.3252050  0.006051757 -0.5687651 -0.1266521
## med_high -0.40315105  0.2249195  0.186362222  0.4002722  0.1243569
## high     -0.48724019  1.0171096 -0.079333958  1.0567350 -0.4911568
##                 age        dis        rad        tax     ptratio
## low      -0.8763374  0.8941028 -0.6947544 -0.7428462 -0.44921851
## med_low  -0.4039546  0.4234694 -0.5422055 -0.4700267 -0.05551182
## med_high  0.4401306 -0.3902071 -0.4065227 -0.2966375 -0.29696463
## high      0.8353906 -0.8435092  1.6382099  1.5141140  0.78087177
##                black       lstat        medv
## low       0.38368498 -0.75302015  0.49746025
## med_low   0.31167860 -0.13033637 -0.01422036
## med_high  0.05748202  0.01581784  0.16881733
## high     -0.61624939  0.90741102 -0.69933165
## 
## Coefficients of linear discriminants:
##                 LD1         LD2         LD3
## zn       0.12429716  0.69753574 -1.08676661
## indus    0.03308534 -0.14148348  0.13250394
## chas    -0.08749391 -0.08730002  0.17014276
## nox      0.32783864 -0.76478327 -1.05103995
## rm      -0.09991114 -0.16357096 -0.09662516
## age      0.27161792 -0.33897543 -0.36267828
## dis     -0.09843482 -0.22843932  0.29254261
## rad      3.19026316  1.01675964 -0.40923712
## tax     -0.01480205 -0.11142125  0.88024354
## ptratio  0.12775748 -0.02921722 -0.16575052
## black   -0.08861513  0.03753831  0.12940586
## lstat    0.20520684 -0.22684242  0.48875493
## medv     0.17946148 -0.39341523 -0.11656291
## 
## Proportion of trace:
##    LD1    LD2    LD3 
## 0.9468 0.0404 0.0129
#the function for lda biplot arrows
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "red", tex = 0.75, choices = c(1,2)){
  heads <- coef(x)
  arrows(x0 = 0, y0 = 0, 
         x1 = myscale * heads[,choices[1]], 
         y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
  text(myscale * heads[,choices], labels = row.names(heads), 
       cex = tex, col=color, pos=3)
}

#target classes as numeric
classes <- as.numeric(train$crime)
#plot the lda results
plot(lda.fit, dimen = 2,col = classes,pch = classes)
lda.arrows(lda.fit, myscale = 2)

We have 4 clasters, so train data was devided in 25% 4 times with crime as target variable. In the plot we see that three clasters are overlapping while the 4rd one in quite far for them. We aslo see that such variables as zn, nox, rad, ptratio have a big impact on the model

# Predictors
#create train set
train <- boston_scaled[ind,]
#create test set 
test <- boston_scaled[-ind,]
#save the correct classes from test data
correct_classes <- c(test$crime)
#remove the crime variable from test data
test <- dplyr::select(test, -crime)
#predict classes with test data
lda.pred <- predict(lda.fit, newdata = test)

# cross tabulate the results
table(correct = correct_classes, predicted = lda.pred$class)
##        predicted
## correct low med_low med_high high
##       1  15      11        1    0
##       2   4      14        9    0
##       3   0       7       15    1
##       4   0       0        0   25
#target classes as numeric
classes <- as.numeric(correct_classes)
#plot the lda results
plot(lda.fit, dimen = 2,col = classes,pch = classes)
lda.arrows(lda.fit, myscale = 2)

In the table we see the relation between the correct classes and the predicted ones. The classifier did not predict the crime rates correctly since predicted numbers are higher than correct. I also tried to vizualize the LDA results for crime in test data and we see that everything is in a mess.

## distances
library(MASS)
data('Boston')
#scale the data
boston_scaled <- scale (Boston)
#euclidean distance matrix
dist_eu <- (boston_scaled)
#look at the summary of the distances
summary(dist_eu)
##       crim                 zn               indus        
##  Min.   :-0.419367   Min.   :-0.48724   Min.   :-1.5563  
##  1st Qu.:-0.410563   1st Qu.:-0.48724   1st Qu.:-0.8668  
##  Median :-0.390280   Median :-0.48724   Median :-0.2109  
##  Mean   : 0.000000   Mean   : 0.00000   Mean   : 0.0000  
##  3rd Qu.: 0.007389   3rd Qu.: 0.04872   3rd Qu.: 1.0150  
##  Max.   : 9.924110   Max.   : 3.80047   Max.   : 2.4202  
##       chas              nox                rm               age         
##  Min.   :-0.2723   Min.   :-1.4644   Min.   :-3.8764   Min.   :-2.3331  
##  1st Qu.:-0.2723   1st Qu.:-0.9121   1st Qu.:-0.5681   1st Qu.:-0.8366  
##  Median :-0.2723   Median :-0.1441   Median :-0.1084   Median : 0.3171  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.:-0.2723   3rd Qu.: 0.5981   3rd Qu.: 0.4823   3rd Qu.: 0.9059  
##  Max.   : 3.6648   Max.   : 2.7296   Max.   : 3.5515   Max.   : 1.1164  
##       dis               rad               tax             ptratio       
##  Min.   :-1.2658   Min.   :-0.9819   Min.   :-1.3127   Min.   :-2.7047  
##  1st Qu.:-0.8049   1st Qu.:-0.6373   1st Qu.:-0.7668   1st Qu.:-0.4876  
##  Median :-0.2790   Median :-0.5225   Median :-0.4642   Median : 0.2746  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.6617   3rd Qu.: 1.6596   3rd Qu.: 1.5294   3rd Qu.: 0.8058  
##  Max.   : 3.9566   Max.   : 1.6596   Max.   : 1.7964   Max.   : 1.6372  
##      black             lstat              medv        
##  Min.   :-3.9033   Min.   :-1.5296   Min.   :-1.9063  
##  1st Qu.: 0.2049   1st Qu.:-0.7986   1st Qu.:-0.5989  
##  Median : 0.3808   Median :-0.1811   Median :-0.1449  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.4332   3rd Qu.: 0.6024   3rd Qu.: 0.2683  
##  Max.   : 0.4406   Max.   : 3.5453   Max.   : 2.9865
#manhattan distance matrix
dist_man <- dist(boston_scaled, method = "manhattan")
#look at the summary of the distances
summary(dist_man)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##  0.2662  8.4832 12.6090 13.5488 17.7568 48.8618
# k-means clustering
km <-kmeans(boston_scaled, centers = 1)
km <-kmeans(boston_scaled, centers = 3)
km <-kmeans(boston_scaled, centers = 2)

# plot the Boston dataset with clusters
pairs(boston_scaled, col=km$cluster)

#determine K
set.seed(123)
library(ggplot2)
#determine the number of clusters
k_max <- 10
#calculate the total within sum of squares
twcss <- sapply(1:k_max, function(k){kmeans(boston_scaled, k)$tot.withinss})
#visualize the results
qplot(x = 1:k_max, y = twcss, geom = 'line')

#k-means clustering
km <-kmeans(boston_scaled, centers = 2)

Based on the calculated distance meajure the k-classtering was maded. On the graph we see a significant change in point 2 - so the optimal number of clastters is 2. On the plot we see the vizualization for 2 clasters - which part of data where belongs.

## 3D plot
model_predictors <- dplyr::select(train, -crime)
# check the dimensions
dim(model_predictors)
## [1] 404  13
dim(lda.fit$scaling)
## [1] 13  3
# matrix multiplication
matrix_product <- as.matrix(model_predictors) %*% lda.fit$scaling
matrix_product <- as.data.frame(matrix_product)

library(plotly)
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:MASS':
## 
##     select
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
plot_ly(x = matrix_product$LD1, y = matrix_product$LD2, z = matrix_product$LD3, type= 'scatter3d', mode='markers')